package com.hstc.servlet;

import javax.mail.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;

/**
 * 处理邮件附件的下载
 */
public class HandleAttachServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        response.setContentType("text/html");
        HttpSession session = request.getSession();
        ServletOutputStream out = response.getOutputStream();
        int msgnum = Integer.parseInt(request.getParameter("msgnum"));
        int bodynum = Integer.parseInt(request.getParameter("bodynum"));
        String filename = request.getParameter("filename");
        Folder folder = (Folder) session.getAttribute("folder");
        try {
            Message msg = folder.getMessage(msgnum+1);
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            Multipart multi = (Multipart) msg.getContent();
            BodyPart bodyPart = multi.getBodyPart(bodynum);
            InputStream is = bodyPart.getInputStream();
            int c = 0;
            while( (c=is.read()) != -1) {
                out.write(c);
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
